package com.sui.bigdata.rtcadmin.configuration;

import com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author YongChen
 * @date 2019/11/6 14:41
 * @description
 * @email yong_chen@sui.com
 */
@Configuration
public class DisconfConfigure {

    @Bean(name="disconf",initMethod = "init",destroyMethod = "destroy")
    public ReloadablePropertiesFactoryBean getReloadablePropertiesFactoryBean() throws Exception {
        Properties disconfPro = new Properties();
        disconfPro.load(this.getClass().getClassLoader().getResourceAsStream("disconf.properties"));
        String filePaths = disconfPro.getProperty("disconf.file.paths");
        String fileNames = disconfPro.getProperty("disconf.file.names");
        List<String> filePathList = null;
        Set<String> fileNameList = null;
        if(!StringUtils.isEmpty(filePaths)){
            filePathList = Arrays.asList(filePaths.split(","));
        }
        if(!StringUtils.isEmpty(fileNames)){
            fileNameList = new HashSet<>();
            fileNameList.addAll(Arrays.asList(fileNames.split(",")));
        }
        ReloadablePropertiesFactoryBean reloadablePropertiesFactoryBean = new ReloadablePropertiesFactoryBean();
        if(filePathList != null || fileNameList != null) {
            String fileListener = disconfPro.getProperty("disconf.file.listener");
            String keyListener = disconfPro.getProperty("disconf.key.listener");
            boolean enableDisconf = Boolean.valueOf(disconfPro.getProperty("disconf.enable.remote.conf", "true"));
            reloadablePropertiesFactoryBean.setEnableDisconf(enableDisconf);
            reloadablePropertiesFactoryBean.setFileListener(fileListener);
            reloadablePropertiesFactoryBean.setKeyListener(keyListener);
            reloadablePropertiesFactoryBean.setPaths(filePathList);
            reloadablePropertiesFactoryBean.setLocations(fileNameList);
        }else{
            throw  new Exception("disconf.file.paths or disconf.file.names缺失");
        }
        return reloadablePropertiesFactoryBean;
    }

}
